import React, { Component } from 'react';
import Button from '@material-ui/core/Button';
import withStyles from '@material-ui/core/styles/withStyles';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router-dom';
import Popover from '@material-ui/core/Popover';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { selectUsers, getUsers } from '../../actions/login-action';
import CircularProgress from '@material-ui/core/CircularProgress';
import Grid from '@material-ui/core/Grid';
import TextField from '@material-ui/core/TextField';
import Typography from '@material-ui/core/Typography';

import img from '../welcome/logo.png';

const styles = theme => ({
  typography: {
    margin: theme.spacing.unit * 2,
  },
});

class Login extends Component {
  static contextTypes = {
    router: PropTypes.object.isRequired,
}
  constructor(props){
    super(props);
    this.state = {
        email: "",
        password: "",
        isSuccess: false,
        progressStyle: {
          display: "none"
        },
        anchorEl: null,
        message: ""
    }
  }

  handleClose = () => {
    this.setState({
      anchorEl: null,
    });
  };

  onClick = (e) => {
      console.log("login clicked");
      console.log(this.props);
      // validate form elements
      
      let flag = this.formValidate(this.state.email, this.state.password, e);
      if(!flag) {
        // validate failed
        return;  
      }
      var that = this;
      // show circular progress
      // this.state.progressStyle.display = "block";
      this.setState({
        progressStyle: {
          display: "block"
        }
      })
      this.props.users(this.state.email, this.state.password).then(function(){
        console.log("dddddddd");
        console.log(that.props);
        // hide circular progress
        // that.state.progressStyle.display = "none";
        that.setState({
          progressStyle: {
            display: "none"
          },
        });
        if(that.props.isSuccess === false) {
          that.setState({
            message: "Login failed. Please make sure you have a valid account!",
            anchorEl: e.currentTarget,
          });
        }else{
          // login success
          that.props.history.push('/welcome');
        }
      });
  };

  emailOnChange = (e) => {
      console.log("onChange");
      this.setState({ 
          email: e.target.value
      });
  };

  passOnChange = (e) => {
    console.log("password onchange");
    this.setState({
      password: e.target.value
    })
  };

  formValidate = (email, password, e) => {
    let reg = new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$"); //正则表达式
    if(!reg.test(email)) {
      console.log("invalid email format");
      this.setState({
        message: "invalid email format",
        anchorEl: e.currentTarget,
      });
      return false;
    }
    // password length should be 4-10
    if(password.length < 4 || password.length > 10) {
      console.log("invalid password length");
      this.setState({
        message: "invalid password length",
        anchorEl: e.currentTarget,
      });
      return false;
    }
    return true;
  };

  render() {
    const { classes } = this.props;
    const { anchorEl } = this.state;
    const open = Boolean(anchorEl);
    return (
      <div>
        {
          <div className="divLoginMainContent">
            <Grid container spacing={24}>
              <Grid item xs={12}>
                <Grid item xs={12} className="formPadding"><img src={img} alt="logo" /></Grid>
                <Grid item xs={12} className="formPadding fontStyle" style={{color: "black"}}>Welcome Back</Grid>
                <Grid item xs={12} className="fontStyle">Sign in to continue</Grid>
                <Grid item xs={12}>
                  <TextField
                    id="standard-name"
                    label="Email"
                    margin="normal"
                    className="formElement" 
                    onChange={this.emailOnChange}
                  />
                </Grid>
                <Grid item xs={12} className="formPadding">
                  <TextField
                    id="standard-password"
                    label="Password"
                    margin="normal"
                    type="password"
                    className="formElement" 
                    onChange={this.passOnChange}
                  />
                </Grid>
                <Grid item xs={12} className="formPadding">
                  <Button className="formElement" variant="contained" color="primary" onClick={ this.onClick }>
                      Login    
                  </Button>
                </Grid>
                
                <div style={this.state.progressStyle}>
                  <CircularProgress />
                </div>
              </Grid>
            </Grid>
            <Popover
          id="simple-popper"
          open={open}
          anchorEl={anchorEl}
          onClose={this.handleClose}
          anchorOrigin={{
            vertical: 'bottom',
            horizontal: 'center',
          }}
          transformOrigin={{
            vertical: 'top',
            horizontal: 'center',
          }}
        >
          <Typography className={classes.typography}>{this.state.message}</Typography>
        </Popover>
          </div>
        }
      </div>
    );
  }
}

const mapStateToProps = state => {
  console.log("mapStateToProps");
  console.log(state);
  
  return {
    isSuccess: state.auth.isSuccess
  }
};

const mapDispatchToProps = (dispatch) => {
  console.log("mapDispatchToProps");
  return bindActionCreators({
    users: selectUsers,
    getusers: getUsers
  }, dispatch)
};

Login.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default connect(mapStateToProps, mapDispatchToProps)(withStyles(styles)(withRouter(Login)));